package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;

public class ClassLoadExpand extends ClassLoader {

    private String location;//资源根目录的绝对路径

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = loadClassData(name);
        return defineClass(name, bytes, 0, bytes.length);
    }

    private byte[] loadClassData(String name) {
        FileInputStream fis = null;
        byte[] datas = null;
        try {
            String filePath = location + File.separator + name.replaceAll("\\.",  Matcher.quoteReplacement(File.separator)) + ".class";
            System.out.println(filePath);
            fis = new FileInputStream(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = fis.read()) != -1) {
                bos.write(b);
            }
            datas = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return datas;
    }

}
